package org.example.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zfj
 * @date 2022/2/21 -11:44
 */
public class Consumer {
	public static void main(String[] args) throws IOException, TimeoutException {
		//所有的中间件技术都是基于tcp/ip协议基础上构建新型的协议规范，
		// 只不过rabbitmq遵循amqp协议
		//ip 端口

		//1.创建连接工程
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("127.0.0.1");
		connectionFactory.setPort(5672);
		connectionFactory.setUsername("admin");
		connectionFactory.setPassword("admin");
		//消息发送到根节点上
		connectionFactory.setVirtualHost("/");
		Connection connection=null;
		Channel channel=null;
		try {
			//2.创建连接Connection
			connection=connectionFactory.newConnection("生产者");
			//3.通过连接获取通道Channel
			channel = connection.createChannel();
			//4.通过创建交换机，声明队列，绑定关系，路由key，发送消息和接收消息
			channel.basicConsume("queue1", true, new DeliverCallback() {
				@Override
				public void handle(String consumerTag, Delivery message) throws IOException {
					System.out.println("收到消息是=" + new String(message.getBody(), "UTF-8"));
				}
			}, new CancelCallback() {
				@Override
				public void handle(String consumerTag) throws IOException {
					System.out.println("接收消息失败....");
				}
			});
			System.out.println("开始运行");
			System.in.read();
		}catch (Exception ex){
			ex.printStackTrace();
		}finally {
			//7.关闭连接
			if(channel!=null&&channel.isOpen()){
				try {
					channel.close();
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			//8.关闭通道
			if(connection!=null&&connection.isOpen()){
				try {
					connection.close();
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		}
	}
}
